package com.lemurian.bankdata.bean;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.entity.Courier;

@Repository
public class CourierDAO extends BaseDaoHibernate<Courier>{
	
	private BankDataLogger log = BankDataLogger.getLogger(CourierDAO.class.getName());

	public Courier load(int id) {
		log.info("Overidden on DAO");
		try {
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Courier.class);
			criteria.createAlias("bpnRegion", "bpnRegion");
			criteria.add(Restrictions.eq("id", id));
			criteria.setCacheable(true);
			
			Courier courier = (Courier) criteria.uniqueResult();
			
			if (courier != null) {
				log.sInfo("courier found with wilayah [%s]", courier.getBpnRegion().getReqionName());
			}
					
			return courier;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public PartialList<Courier> findByCriteria(int start, int count, Order order, Criterion... criterion){
		PartialList<Courier> partialList = null;
		try {
			log.info("Get overidden on DAO");
			// total
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Courier.class);
			criteria.createAlias("bpnRegion", "bpnRegion");
			
			criteria.setCacheable(true);
			for (Criterion c : criterion) {
				criteria.add(c);
			}
			criteria.setProjection(Projections.rowCount());
			int total = ((Integer) criteria.list().iterator().next()).intValue();
			// partial data
			criteria = sessionFactory.getCurrentSession().createCriteria(Courier.class);
			criteria.createAlias("bpnRegion", "bpnRegion");
			criteria.setCacheable(true);
			for (Criterion c : criterion) {
				criteria.add(c);
			}
			if (order!=null) criteria.addOrder(order);
			criteria.setFirstResult(start);
			criteria.setMaxResults(count);
			
			partialList = new PartialList<Courier>(criteria.list(), total);
		} catch(Exception exception){
			exception.printStackTrace();
			//sessionFactory.getCurrentSession().getTransaction().rollback();
		}
		return partialList;
	}
}